package pt.uma.gap.plugin;

import java.util.List;
import java.util.logging.Logger;

import org.eclipse.core.commands.ExecutionEvent;
import org.eclipse.core.commands.ExecutionException;
import org.eclipse.core.commands.IHandler;
import org.eclipse.core.commands.IHandlerListener;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Status;
import org.eclipse.core.runtime.jobs.Job;
import org.eclipse.jdt.core.ICompilationUnit;

import pt.uma.gap.accessperm.GenAccessPermissionCUAnalysis;
import pt.uma.gap.accessperm.WorkspaceUtilities;




public class GAPHandler implements IHandler{

	@SuppressWarnings("unused")
	private static final Logger log = Logger.getLogger(GAPHandler.class.getName());
	
	@Override
	public void addHandlerListener(IHandlerListener handlerListener) { }

	@Override
	public void dispose() { }

	@Override
	public Object execute(ExecutionEvent event) throws ExecutionException {
		
		//Check Context, Read Context = 0; Read Write Context = 1
		int contextType = 0;
		if(event.getCommand().getId().endsWith(".RW.Context")){
			contextType = 1;
		}
		
		//Mast be final to enter on Job
		final int contextTypef = contextType;

		//Lunch Eclipse Job 
		Job j = new Job("GAP") {

			@Override
			protected IStatus run(IProgressMonitor monitor) {
				
				//Load all compilation unit(files) form workspace 
				final List<ICompilationUnit> cus = WorkspaceUtilities.scanForCompilationUnits();

				GenAccessPermissionCUAnalysis genAccessPermissionCUAnalysis = new GenAccessPermissionCUAnalysis();
				
				//Generate Access permission
				genAccessPermissionCUAnalysis.analyzeCompilationUnit(cus, contextTypef);
				
				if(monitor.isCanceled())
					return Status.CANCEL_STATUS;
				return Status.OK_STATUS;
			}
			
		};
		j.setUser(true);
		j.schedule();
		
		return null;
		
		
	}

	@Override
	public boolean isEnabled() {
		return true;
	}

	@Override
	public boolean isHandled() {
		return true;
	}

	@Override
	public void removeHandlerListener(IHandlerListener handlerListener) {

		
	}
	


}
